const express = require('express')
const authenticateToken = require('../utils/authMiddleware.js') // 引入身份验证中间件
const xlsx = require('xlsx')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath, createExcelFileIfNotExists } = require('../utils/constants.js') // 引入常量
const { v4: uuidv4 } = require('uuid')
const fs = require('fs')
const router = express.Router()
// 使用绝对路径
const usersFilePath = getFilePath('users')
const followersFilePath = getFilePath('followers')

// 初始化 Followers 文件
createExcelFileIfNotExists(followersFilePath, 'followers')

// 关注用户接口 (需要身份验证)
router.post('/followUser', authenticateToken, (req, res) => {
  const { targetUserId } = req.body // 被关注的用户ID
  const currentUserId = req.user.id // 当前登录用户的ID

  if (!targetUserId) {
    return sendResponse(res, 400, {}, '请提供要关注的用户ID。')
  }

  const usersWorkbook = xlsx.readFile(usersFilePath)
  const usersWorksheet = usersWorkbook.Sheets['Users']
  const usersData = xlsx.utils.sheet_to_json(usersWorksheet)

  const targetUser = usersData.find((user) => user.ID === targetUserId)
  if (!targetUser) {
    return sendResponse(res, 404, {}, '未找到该用户。')
  }

  // 更新 Followers 文件
  const followersWorkbook = xlsx.readFile(followersFilePath)
  const followersWorksheet = followersWorkbook.Sheets['followers']
  const followersData = xlsx.utils.sheet_to_json(followersWorksheet)

  // 检查是否已经存在关注记录
  const alreadyFollowing = followersData.some((follow) => follow.UserID === targetUserId && follow.FollowerID === currentUserId)
  if (alreadyFollowing) {
    return sendResponse(res, 400, {}, '您已经关注了该用户。')
  }

  // 添加新的关注记录
  const newFollower = {
    ID: uuidv4(),
    UserID: targetUserId,
    FollowerID: currentUserId
  }
  followersData.push(newFollower)

  // 更新 Excel 数据
  const updatedFollowersSheet = xlsx.utils.json_to_sheet(followersData)
  followersWorkbook.Sheets['followers'] = updatedFollowersSheet
  xlsx.writeFile(followersWorkbook, followersFilePath)

  return sendResponse(res, 200, {}, '关注成功。')
})

module.exports = router
